import axios from 'axios'
import store from '../store'
import router from '../router'
import CONFIG from '../config/index.js'
import {
  Notification,
  Loading
} from 'element-ui';

const CancelToken = axios.CancelToken
var cancel, loadingInstance;
var service = axios.create({
  // baseURL: `${window.location.protocol}//${window.location.host}`, // 本地,结尾不能带/
  baseURL: CONFIG.domain, // 线上,结尾不能带/
  // baseURL: 'http://47.98.100.11:3001/mock/17', // YAPI环境,结尾不能带/
  changeOrigin: true,
  timeout: 15000,
  withCredentials: false, // 发送cookie
  headers: {
    'Content-Type': 'application/json;charset=utf-8', // 指定传参格式，勿删
  }
})
//添加请求拦截器
service.interceptors.request.use(config => {
  if (sessionStorage.getItem('token')) {
    config.headers.token = sessionStorage.getItem('token')
  }

  // 数据加载遮罩层动画
  // let options = {
  //   target: document.querySelector('.mainContent'),
  //   text: '拼命加载中。。。',
  //   background: 'rgba(0, 0, 0, 0.8)',
  //   spinner: "el-icon-loading"
  // };
  // loadingInstance = Loading.service(options); // 开始加载动画
  return config
}, function (error) {
  return Promise.reject(error)
})
//添加响应拦截器
service.interceptors.response.use(response => {
  let token = response.data.token;
  if (token) {
    sessionStorage.setItem('token', token)
  }
  /**
  * 下面的注释为通过在response里，自定义code来标示请求状态
  * 当code返回如下情况则说明权限有问题，登出并返回到登录页
  * 如想通过xmlhttprequest来状态码标识 逻辑可写在下面error中
  */
  response => {
    const res = response.data
  }

  // this.$nextTick(() => { // 以服务的方式调用的 Loading 需要异步关闭
  //   loadingInstance.close(); // 关闭加载动画
  // });

  // 255:未登录;
  if (response.status !== 200) {
    Notification({
      message: response.data.msg || response.data.error || '系统未知错误',
      type: 'error'
    })
    // window.location.href = window.location.origin + '/login'
  } else {
    return response
  }
}, error => {
 // console.log(error.response.status)
  if (error.response.status === 401) {
    Notification({
      message: '对不起，请先登录',
      type: 'error'
    })
    // window.location.href = window.location.origin + '/login'
    if(router.currentRoute.fullPath !== "/login"){
      sessionStorage.setItem("redirect", router.currentRoute.fullPath)
    }
    router.push({
      path: '/login',
    })
  } else if (error.response.status === 403) {
    Notification({
      message: '对不起，登录过期，请重新登录',
      type: 'error'
    })
    // window.location.href = window.location.origin
    if(router.currentRoute.fullPath !== "/login"){
      sessionStorage.setItem("redirect", router.currentRoute.fullPath)
    }
    router.push({
      path: '/login',
    })
  } else {
    // if (error.response.status !== 200) {
    //   Notification({
    //     message: error.response.data.message || '系统未知错误',
    //     type: 'error'
    //   })
    //   return Promise.reject('error')
    // } else {
    //   return error.response
    // }
  }

})
export default {
  //get请求
  get(url, data) {
    return new Promise((resolve, reject) => {
      service({
        method: 'get',
        url,
        params: data,
        cancelToken: new CancelToken(c => {
          cancel = c
        })
      }).then(res => { //axios返回的是一个promise对象
        if (res) {
          resolve(res.data)
        } //resolve在promise执行器内部
      }).catch(err => {
        // console.log(err, '异常')
      }).finally(() => {})
    })
  },
  //post请求
  post(url, data) {
    return new Promise((resolve, reject) => {
      service({
        method: 'post',
        url,
        data: data,
        cancelToken: new CancelToken(c => {
          cancel = c
        })
      }).then(res => {
        if (res) {
          resolve(res.data)
        } //resolve在promise执行器内部
      }).catch(err => {
        // console.log(err, '异常')
      }).finally(() => {})
    })
  }
}